package core

import (
	"chatgpt/utils"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"strconv"
	"sync"
)

// wg
var wg sync.WaitGroup

// proxyAddr
// 代理配置
var proxyAddr string = utils.GetProxyServer()

// apiKey
// GPT Api Key
var apiKey string = utils.GetConfig("gpt", "api_key", "")

// privateKey
// 签名密钥
var privateKey string = utils.GetConfig("init", "private_key", "")

// TimeoutValue
// 超时配置
var TimeoutValue string = utils.GetConfig("init", "timeout", "10")

// Action
// 处理请求
//
//	@param w
//	@param r
func Handler(w http.ResponseWriter, r *http.Request) {
	w.Header().Add("Access-Control-Allow-Origin", "*")
	w.Header().Add("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS")
	w.Header().Add("Content-Type", "application/json")
	Timeout, _ := strconv.Atoi(TimeoutValue)
	if r.Method == "POST" {
		var request Request
		raw, _ := ioutil.ReadAll(r.Body)
		json.Unmarshal(raw, &request)

		if privateKey != "" && request.Sign != MakeSign(request, privateKey) {
			fmt.Fprintln(w, BuildResponse(privateKey, 0, "签名错误", ResponseData{}))
			return
		}

		question := utils.Base64{
			Content: []byte(request.Words),
		}.Decode()
		if len(question) > 0 {
			gpt := &GPT{
				ApiKey:  apiKey,
				Proxy:   proxyAddr,
				Timeout: Timeout,
			}

			wg.Add(1)
			go func() {
				defer wg.Done()
				if result, err := gpt.GetAnswer(question); err == nil {
					fmt.Fprintln(w, BuildResponse(privateKey, 1, "请求成功", ResponseData{
						"answer": result.Choices,
					}))
				} else {
					fmt.Fprintln(w, BuildResponse(privateKey, 0, "网络错误", ResponseData{}))
				}
			}()
			wg.Wait()
			return
		}
	}
	fmt.Fprintln(w, BuildResponse(privateKey, 0, "未知错误", ResponseData{}))
}
